package com.btech.dftp.dataimport;

import java.io.File;
import java.sql.Date;
import java.text.ParseException;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;

import org.quincy.rock.core.SpringContext;
import org.quincy.rock.core.util.IOUtil;
import org.quincy.rock.core.util.MapUtil;

import com.btech.dftp.dataimport.excel.DetailExcelReader;
import com.btech.dftp.dataimport.task.ImportGoodsTask;

/**
 * Hello world!
 *
 */
public class App {
	public static SpringContext context = SpringContext.createSpringContext("/spring-dftp.xml");

	public static void main(String[] args) throws Exception {
		String fileName = args.length > 0 ? args[0] : "d:/aa.xlsx";
		//System.out.println(cmdline("d:\\wks\\data")); 
		importGoods(fileName);		
	}
	
	private static String cmdline(String dir) {
		StringBuilder sb=new StringBuilder();
		sb.append("java -Dfile.encoding=UTF-8 -classpath \"");
		sb.append(dir);
		sb.append(";");
		sb.append(dir);
		sb.append("\\dftp-import.jar");
		File lib=new File(dir,"lib");
		for (File jar:lib.listFiles()) {
			sb.append(";");
			sb.append(jar.getAbsolutePath());		
		}	
		sb.append("\" com.btech.dftp.dataimport.App");
		return sb.toString();
	}
	
	private static void importGoods(String fileName) throws Exception {
		final ImportGoodsTask task = context.getBean(ImportGoodsTask.class);
		final Set<String> finished = new HashSet<String>(); //完成的
		final Set<String> repeated = new HashSet<String>(); //重复的
		DetailExcelReader reader = new DetailExcelReader(fileName);
		task.setBatchSize(reader.getBatchSize());
		System.out.println("Start importing data...");
		reader.forEach(new Consumer<Map<String, Object>>() {

			public void accept(Map<String, Object> data) {
				String declarationNo = MapUtil.getString(data, "declarationNo");
				if (finished.contains(declarationNo)) {
					repeated.add(declarationNo);
				} else {
					finished.add(declarationNo);
					task.processData(data);
				}
			}
		});
		task.finish();
		if (repeated.size() > 0) {
			System.out.println(repeated.size() + " duplicate data are found in this import:");
			for (String no : repeated) {
				System.out.println(no);
			}
		}
		IOUtil.closeQuietly(reader);
	}
}
